package com.letoo.sso.dataaccess.dao.cahce.impl;

import java.io.UnsupportedEncodingException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import com.alibaba.fastjson.JSON;
import com.letoo.sso.dataaccess.dao.cahce.BaseCacheDAO;

/**
 * 
 * @author dengjie
 *
 * @param <K>
 * @param <V>
 */
public class BaseCacheDAOImpl implements BaseCacheDAO {

  private static final Logger LOGGER = LoggerFactory.getLogger(BaseCacheDAOImpl.class);

  @Autowired
  private StringRedisTemplate redisTemplate;

  protected byte[] serialize(Object obj) {
    if (obj instanceof String) {
      return redisTemplate.getStringSerializer().serialize((String) (obj));
    } else {
      return JSON.toJSONBytes(obj);
    }
  }

  @SuppressWarnings("unchecked")
  protected <T> T deserialize(Class<T> type, byte[] bytes) {
    if (bytes == null) {
      return null;
    }
    if (type == String.class) {
      return (T) redisTemplate.getStringSerializer().deserialize(bytes);
    } else {
      return JSON.parseObject(bytes, type);
    }
  }

  protected <T> List<T> deserializeArray(Class<T> type, byte[] bytes) {
    if (bytes == null) {
      return null;
    }
    try {
      return (List<T>) JSON.parseArray(new String(bytes, "UTF-8"), type);
    } catch (UnsupportedEncodingException e) {
      LOGGER.error("DeserializeArray error");
    }
    return null;
  }

  public StringRedisTemplate getRedisTemplate() {
    return redisTemplate;
  }

  public void setRedisTemplate(StringRedisTemplate redisTemplate) {
    this.redisTemplate = redisTemplate;
  }

}
